package com.oracle.application.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * Created by huyiran on 2018/8/18.
 */
public class CommonUtil {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DATE_NOMAL_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter DATE_TIME_CONTINUE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    private static final DateTimeFormatter DATE_CONTINUE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    private static final String RANDOM_SEED_ALL = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String RANDOM_VERIFICATION_CODE = "0123456789abcdefghijklmnopqrstuvwxyz";

    private static final Random RANDOM = new Random();

    /**
     * 获取随机数字（数字）
     * @param num 字符串位数
     * @return
     */
    public static String randomNumber(Integer num) {
        return randomValue(num, 1);
    }

    /**
     * 获取随机字符串（数字 + 大小写字母）
     * @param num 字符串位数
     * @return
     */
    public static String randomString(Integer num) {
        return randomValue(num, 0);
    }

    /**
     * 生成随机字符串
     * @param num 字符串位数
     * @param type 字符串类型：0-数字+大小写字母
     * @return
     */
    private static String randomValue(Integer num, Integer type) {
        char[] chars = new char[num];
        int len = type == 0 ? RANDOM_SEED_ALL.length() : 10;
        for (int i = 0; i < num; i++) {
            chars[i] = RANDOM_SEED_ALL.charAt(RANDOM.nextInt(len));
        }
        return new String(chars);
    }

    /**
     * 获取当前时间并格式化
     * @return
     */
    public static String getNowTime() {
        return localDateTimeToDateTimeString(LocalDateTime.now());
    }

    public static String getNowDate() {
        return LocalDateTime.now().format(DATE_CONTINUE_FORMATTER);
    }

    public static String getNowDateTime() {
        return LocalDateTime.now().format(DATE_TIME_CONTINUE_FORMATTER);
    }

    public static Long localDateTimeToTimestamp(LocalDateTime localDateTime) {
        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    public static LocalDateTime TimestampTolocalDateTime(Long timestamp) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.of("+8"));
    }

    public static String localDateTimeToDateTimeString(LocalDateTime localDateTime) {
        return localDateTime.format(DATE_TIME_FORMATTER);
    }

    public static String localDateTimeToDateString(LocalDateTime localDateTime) {
        return localDateTime.format(DATE_NOMAL_FORMATTER);
    }

    public static LocalDateTime dateTimeStringToLocalDateTime(String dateTimeString) {
        return LocalDateTime.parse(dateTimeString, DATE_TIME_FORMATTER);
    }

    /**
     * 生成随机验证码（数字 + 小写字母）
     * @param num 字符串位数
     * @return
     */
    public static String randomVerificationCode(Integer num) {
        char[] chars = new char[num];
        for (int i = 0; i < num; i++) {
            chars[i] = RANDOM_VERIFICATION_CODE.charAt(RANDOM.nextInt(RANDOM_VERIFICATION_CODE.length()));
        }
        return new String(chars);
    }

    public static String getRealIP(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                // 根据网卡取本机配置的IP
                InetAddress inet = null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP，多个IP按照','分割
        if(ipAddress != null && ipAddress.indexOf(",") != -1) { // "***.***.***.***".length() = 15
            ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
        return ipAddress;
    }
}
